package cn.lzd.ui.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import cn.lzd.ui.R;
import cn.lzd.ui.utils.GlideUtil;
import com.blankj.utilcode.util.SizeUtils;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lizhidong
 * 自动翻滚广告页，带可自定义翻滚指示器
 */
public class RollAdView extends ConstraintLayout {
    /**
     * 轮换间隔
     */
    private final static int rollTime = 4;
    /**
     * 底部点的大小
     */
    private final int dotUnSelectSize;
    private final int dotSelectSize;
    private final ScaleType scaleType;
    /**
     * 底部点间距
     */
    private final int dotMargin;
    private final float mainDimension;
    private Drawable dotSelectDrawable;
    private Drawable dotUnSelectDrawable;
    /**
     * 圆角尺寸
     */
    private final int mRadius;
    /**
     * 滚动任务执行器
     */
    private Disposable rollDisposable;
    // region 页面状态
    private boolean isRolling = false;
    private int nowPos;
    // endregion
    private ViewPager viewPager;
    private PagerAdapter mAdapter;
    private final List<DataBean> values = new ArrayList<>();
    private LinearLayout dotContainer;

    public RollAdView(@NonNull Context context) {
        this(context, null);
    }

    public RollAdView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RollAdView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RollAdView);
        dotUnSelectSize = typedArray.getDimensionPixelSize(R.styleable.RollAdView_rav_dotSize
                , SizeUtils.dp2px(4));
        dotSelectSize = typedArray.getDimensionPixelSize(R.styleable.RollAdView_rav_selectDotSize
                , SizeUtils.dp2px(14));
        dotMargin = typedArray.getDimensionPixelSize(R.styleable.RollAdView_rav_dotMargin
                , SizeUtils.dp2px(5));
        dotSelectDrawable = typedArray.getDrawable(R.styleable.RollAdView_rav_selectDotSrc);
        dotSelectDrawable = dotSelectDrawable != null ? dotSelectDrawable : ContextCompat.getDrawable(context, R.drawable.uibase_circle_red);
        String dimensionString = typedArray.getString(R.styleable.RollAdView_rav_dimension);
        float dimension;
        try {
            dimension = Float.parseFloat(dimensionString);
        } catch (Exception ignore) {
            dimension = -1f;
        }
        mainDimension = dimension;
        dotUnSelectDrawable = typedArray.getDrawable(R.styleable.RollAdView_rav_dotSrc);
        dotUnSelectDrawable = dotUnSelectDrawable != null ? dotUnSelectDrawable : ContextCompat.getDrawable(context, R.drawable.uibase_circle_gray);
        scaleType = ScaleType.getByType(typedArray.getInt(R.styleable.RollAdView_rav_scaleType, 1));
        mRadius = typedArray.getDimensionPixelSize(R.styleable.RollAdView_rav_radius, 0);
        typedArray.recycle();

        initView(context);
    }

    private enum ScaleType {
        FIT_XY(1), CENTER_CROP(6);

        final int i;

        ScaleType(int i) {
            this.i = i;
        }

        static ScaleType getByType(int i) {
            for (ScaleType scaleType : values()) {
                if (scaleType.i == i) {
                    return scaleType;
                }
            }
            return FIT_XY;
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (mainDimension == -1) {
            viewPager.setPadding(0, 0, 0, 0);
        } else {
            int height = bottom - top;
            int itemWidth = (int) (height * mainDimension);
            int offset = (right - left - itemWidth) / 2;
            viewPager.setPadding(offset, 0, offset, 0);
        }
    }

    private void initView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.uibase_roll_ad_layout, this, false);
        dotContainer = view.findViewById(R.id.uibase_roll_ad_dot_container);
        viewPager = view.findViewById(R.id.uibase_roll_ad_main);
        if (mainDimension != -1) {
            viewPager.setClipChildren(false);
            viewPager.setClipToPadding(false);
        }
        mAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return isEmptyValue() ? 0 : values.size() + 2;
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                Context mContext = container.getContext();
                RoundImageView view = new RoundImageView(mContext);
                view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

                if (isEmptyValue()) {
                    return view;
                }
                DataBean value = values.get(getRealPosition(position));
                view.setUseCenterCrop(scaleType == ScaleType.CENTER_CROP);
                view.setRadius(mRadius);
                GlideUtil.loadUrl2Img(value.pic, view);
                view.setOnClickListener(value.onClickListener);
                container.addView(view);
                return view;
            }

            @Override
            public int getItemPosition(@NonNull Object object) {
                return POSITION_NONE;
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView((View) object);
            }
        };
        viewPager.setAdapter(mAdapter);
        viewPager.setPageMargin(SizeUtils.dp2px(8));
        nowPos = 1;
        viewPager.setCurrentItem(nowPos);
        viewPager.addOnPageChangeListener(new PageChangeListener());
        this.addView(view);
    }

    private void nextPage() {
        if (isEmptyValue()) {
            return;
        }
        viewPager.setCurrentItem(nowPos + 1);
    }

    public void setValues(List<DataBean> values) {
        this.values.clear();
        this.values.addAll(values);
        initDotContainer();
        mAdapter.notifyDataSetChanged();
        nowPos = 1;
        viewPager.setCurrentItem(nowPos, false);
    }

    private void initDotContainer() {
        dotContainer.removeAllViews();
        if (isEmptyValue() || values.size() <= 1) {
            return;
        }
        int size = values.size();
        for (int i = 0; i < size; i++) {
            ImageView iv = new ImageView(getContext());
            iv.setImageDrawable(i == 0 ? dotSelectDrawable : dotUnSelectDrawable);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    i == 0 ? dotSelectSize : dotUnSelectSize, dotUnSelectSize);
            if (i != 0) {
                params.setMargins(dotMargin, 0, 0, 0);
            }
            iv.setLayoutParams(params);
            dotContainer.addView(iv);
        }
    }

    private boolean isEmptyValue() {
        return values == null || values.isEmpty();
    }

    private int getRealPosition(int position) {
        if (position == 0) {
            return values.size() - 1;
        } else if (position == values.size() + 1) {
            return 0;
        } else {
            return position - 1;
        }
    }

    class PageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            int lastPos = getRealPosition(nowPos);
            ImageView lastIv = (ImageView) dotContainer.getChildAt(lastPos);
            if (lastIv == null) {
                return;
            }
            LinearLayout.LayoutParams lastLp = (LinearLayout.LayoutParams) lastIv.getLayoutParams();
            lastLp.width = dotUnSelectSize;
            lastIv.setLayoutParams(lastLp);
            lastIv.setImageDrawable(dotUnSelectDrawable);

            int realPos = getRealPosition(position);
            ImageView nowIv = (ImageView) dotContainer.getChildAt(realPos);
            LinearLayout.LayoutParams nowLp = (LinearLayout.LayoutParams) nowIv.getLayoutParams();
            nowLp.width = dotSelectSize;
            nowIv.setLayoutParams(nowLp);
            nowIv.setImageDrawable(dotSelectDrawable);
            nowPos = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (state != ViewPager.SCROLL_STATE_IDLE) {
                isRolling = true;
            } else {
                if (isRolling) {
                    if (isEmptyValue()) {
                        return;
                    }
                    if (nowPos == 0) {
                        viewPager.setCurrentItem(values.size(), false);
                    } else if (nowPos == values.size() + 1) {
                        viewPager.setCurrentItem(1, false);
                    }
                }
                isRolling = false;
            }
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (rollDisposable != null) {
            rollDisposable.dispose();
        }
        rollDisposable = Observable.interval(rollTime, TimeUnit.SECONDS)
                .filter(along -> !isRolling && values.size() > 1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> nextPage());
    }

    @Override
    protected void onDetachedFromWindow() {
        if (rollDisposable != null) {
            rollDisposable.dispose();
        }
        setValues(new LinkedList<>());
        super.onDetachedFromWindow();
    }

    public static class DataBean {
        public String pic;
        public OnClickListener onClickListener;

        public DataBean(String pic, OnClickListener onClickListener) {
            this.pic = pic;
            this.onClickListener = onClickListener;
        }
    }
}
